﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Security.Cryptography;

namespace VersionManage.Common
{
    /// <summary>
    /// 签名
    /// </summary>
    public class EncryptUtil 
    {
        /// <summary>生成有效签名</summary>
        public static string Signature(IDictionary<string, string> paras, string secret)
        {
            //签名结果
            string result = null;

            //需要签名的数据不为空
            if (paras != null)
            {
                //可排序的键值对类
                IDictionary<string, string> treeMap = new SortedList<string, string>();
                foreach (KeyValuePair<string, string> kvp in paras)
                {
                    treeMap.Add(kvp.Key, kvp.Value);
                }

                IEnumerator iter = treeMap.Keys.GetEnumerator();
                StringBuilder orgin = new StringBuilder();
                while (iter.MoveNext())
                {
                    string name = (string)iter.Current;
                    string value = treeMap[name];
                    orgin.Append(name.ToLower()).Append(value);
                }

                try
                {
                    result = Md5Hex(orgin.ToString()).ToUpper();
                    //加上密钥MD5
                    result = Md5Hex(result + secret).ToUpper();
                }
                catch (System.Exception)
                {
                    throw new System.Exception("sign error !");
                }
            }
            return result;
        }

        /// <summary>生成有效签名</summary>
        /// <param name="@params"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string SignaturePassport(IDictionary<string, string> paras, string secret)
        {
            //签名结果
            string result = null;

            //需要签名的数据不为空
            if (paras != null)
            {
                //可排序的键值对类
                IDictionary<string, string> treeMap = new SortedList<string, string>();
                foreach (KeyValuePair<string, string> kvp in paras)
                {
                    treeMap.Add(kvp.Key, kvp.Value);
                }

                IEnumerator iter = treeMap.Keys.GetEnumerator();
                StringBuilder orgin = new StringBuilder();
                while (iter.MoveNext())
                {
                    string name = (string)iter.Current;
                    string value = treeMap[name];
                    {
                        orgin.Append(value);
                    }
                }

                try
                {
                    //加上密钥MD5
                    result = Md5Hex(orgin.ToString() + secret).ToLower();
                }
                catch (System.Exception)
                {
                    throw new System.Exception("sign error !");
                }
            }
            return result;
        }

        /// <summary>绑定店铺-生成有效签名</summary>
        /// <param name="@params"></param>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static string SignatureBindNode(IDictionary<string, string> paras, string secret)
        {
            //签名结果
            string result = null;

            //需要签名的数据不为空
            if (paras != null)
            {
                //可排序的键值对类
                IDictionary<string, string> treeMap = new SortedList<string, string>();
                foreach (KeyValuePair<string, string> kvp in paras)
                {
                    treeMap.Add(kvp.Key, kvp.Value);
                }

                IEnumerator iter = treeMap.Keys.GetEnumerator();
                StringBuilder orgin = new StringBuilder();
                while (iter.MoveNext())
                {
                    string name = (string)iter.Current;
                    string value = treeMap[name];
                    orgin.Append(value);
                }

                try
                {
                    //加上密钥MD5
                    result = Md5Hex(orgin.ToString() + secret).ToLower();
                }
                catch (System.Exception)
                {
                    throw new System.Exception("sign error !");
                }
            }
            return result;
        }

        /// <summary>
        /// MD5加密并输出十六进制字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Md5Hex(string str)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(Encoding.UTF8.GetBytes(str));

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                //转化为十六进制字符
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString().ToUpper();
        }

     
        /// <summary>
        ///  根据证书获取token
        /// </summary>
        /// <param name="certiId"></param>
        /// <returns></returns>
        //public static string GetToken(string certiId)
        //{
        //    IDictionary<string, string> paras = new Dictionary<string, string>();
        //    paras.Add("certi_app", "certi.get_token");
        //    paras.Add("certificate_id", certiId);
        //    paras.Add("format", "json");
        //    paras.Add("certi_ac", EncryptUtil.SignaturePassport(paras, "GMGetToken"));

        //    string result = string.Empty;
        //    string token = string.Empty;
        //    JavaScriptSerializer js = new JavaScriptSerializer();
        //    LicesenModel model = null;

        //    try
        //    {
        //        result = new WebUtils().DoPost(Configuration.licesenUrl(), WebUtils.BuildQuery(paras));
        //        model = js.Deserialize<LicesenModel>(result);
        //        if (model.res == "succ")
        //        {
        //            model = js.Deserialize<LicesenSuccModel>(result);
        //            token = ((LicesenSuccModel)model).info.token;
        //        }
        //        else
        //        {
        //            model = js.Deserialize<LicesenFailModel>(result);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        LogWrite.WriteLog(ex, "GetToken，json字符【" + result + "】");
        //    }
        //    return token;
        //}
    }
}
